<script setup>
import { getElementSize } from '@/views/study/three/composables'
import { useResizeObserver } from '@vueuse/core'
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

const webgl = ref(null)

let renderer = null
let camera = null

onMounted(() => {
  const { width, height } = getElementSize(webgl)

  const scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(30, width / height, 0.1, 1000)

  camera.position.set(0, 0, 100)

  const material = new THREE.LineBasicMaterial({ color: '#156289' })

  const points = []
  points.push(new THREE.Vector3(-10, 0, 0))
  points.push(new THREE.Vector3(-5, 5, 0))
  points.push(new THREE.Vector3(0, 0, 0))
  points.push(new THREE.Vector3(10, 10, 0))
  points.push(new THREE.Vector3(7, 10, 0))
  points.push(new THREE.Vector3(10, 10, 0))
  points.push(new THREE.Vector3(10, 7, 0))

  const geometry = new THREE.BufferGeometry().setFromPoints(points)
  const line = new THREE.Line(geometry, material)

  scene.add(line)

  renderer = new THREE.WebGLRenderer()
  renderer.setSize(width, height)
  renderer.render(scene, camera)
  webgl.value.appendChild(renderer.domElement)

  const orbit = new OrbitControls(camera, renderer.domElement)
  orbit.enableDamping = true

  function render() {
    requestAnimationFrame(render)

    orbit.update()

    renderer.render(scene, camera)
  }

  render()
})

function resizeHandler() {
  const { width, height } = getElementSize(webgl)

  camera.aspect = width / height
  camera.updateProjectionMatrix()

  renderer.setSize(width, height)
}

useResizeObserver(webgl, () => {
  resizeHandler()
})
</script>

<template>
  <div ref="webgl" />
</template>
